using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Rilisoft.MiniJson;
using UnityEngine;

public class LikeModeManager : MonoBehaviour
{
	public enum ServerResponse
	{
		Successful = 0,
		WrongFormat = 1,
		ServerFail = 2
	}

	private const string SFN_LIKE_MODE_STATUS_LIST = "likeModeStatusList";

	private const string SFN_LIKE_MODE_RATING = "likeModeRating";

	public static LikeModeManager instance;

	private Dictionary<TypeGame, bool> _likeStatusList;

	private Dictionary<TypeGame, bool> _oldLikeStatusList;

	private Dictionary<TypeGame, bool> _likeStatusToSend;

	private string _responseResult = string.Empty;

	private Dictionary<int, int> _likeModesRating;

	private Coroutine _sendCoroutine;

	private bool _blockSend;

	public Dictionary<int, int> LikeModesRating
	{
		get
		{
			if (_likeModesRating == null)
			{
				_likeModesRating = ResponseDictionayeParser((!string.IsNullOrEmpty(_responseResult)) ? _responseResult : BCWStorage.Get<string>("likeModeRating"));
			}
			return _likeModesRating;
		}
	}

	private void Awake()
	{
		instance = this;
		StartCoroutine(InitLikeModesCoroutine());
	}

	private void OnDestroy()
	{
		instance = null;
	}

	public bool GetLikeStatus(TypeGame typeGame)
	{
		Init();
		return _likeStatusList.ContainsKey(typeGame) && _likeStatusList[typeGame];
	}

	public void SetLikeStatus(TypeGame TypeGame, bool status)
	{
		Init();
		_likeStatusList[TypeGame] = status;
		Send();
	}

	public void Save(bool immediatelySave = false)
	{
		List<int> list = new List<int>();
		foreach (KeyValuePair<TypeGame, bool> likeStatus in _likeStatusList)
		{
			if (likeStatus.Value)
			{
				list.Add(BCWServer.GetIdModeByTypeGame(likeStatus.Key));
			}
		}
		BCWStorage.Set("likeModeStatusList", Json.Serialize(list), immediatelySave);
	}

	public void Send()
	{
		if (_sendCoroutine != null)
		{
			StopCoroutine(_sendCoroutine);
			_sendCoroutine = null;
		}
		else
		{
			GameModesUI.OnStartMode += SendImmediately;
		}
		_sendCoroutine = StartCoroutine(SendCoroutine());
	}

	private IEnumerator SendCoroutine()
	{
		yield return new WaitForSeconds(3f);
		GameModesUI.OnStartMode -= SendImmediately;
		SendImmediately();
	}

	public void SendImmediately()
	{
		if (_sendCoroutine != null)
		{
			StopCoroutine(_sendCoroutine);
			_sendCoroutine = null;
		}
		if (!_blockSend && _checkSend())
		{
			_blockSend = true;
			StartCoroutine(SendImmediatelyCoroutine());
		}
	}

	private IEnumerator SendImmediatelyCoroutine()
	{
		if (BCWServer.TryParseIdPlayer(BCWServer.idPlayer))
		{
			string requestStr = SerializeMessages(_likeStatusToSend);
			Log(requestStr);
			WWWForm form = new WWWForm();
			form.AddField("action", "set_rating_mode");
			form.AddField("id", BCWServer.idPlayer);
			form.AddField("rating", requestStr);
			form.AddField("app_version", BCWServer._version);
			WWW www = new WWW(headers: new Dictionary<string, string> { 
			{
				"Authorization",
				BCWServer.HashForPush(form.data)
			} }, url: URLs.bcwServer, postData: form.data);
			if (www == null)
			{
				Log("set_rating_mode Error www download");
				yield break;
			}
			yield return www;
			string result = BCWServer.Sanitize(www);
			if (!string.IsNullOrEmpty(www.error))
			{
				Log("set_rating_mode Error download:  " + www.error);
			}
			else if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
			{
				Log("set_rating_mode failed ");
			}
			else if (string.IsNullOrEmpty(result))
			{
				Log("set_rating_mode result is empty");
			}
			else
			{
				Log("set_rating_mode result " + result);
				int resultInt = -1;
				ServerResponse resultStatus = ServerResponse.ServerFail;
				if (int.TryParse(result, out resultInt) && resultInt == 0)
				{
					Save(true);
					_oldLikeStatusList = new Dictionary<TypeGame, bool>(_likeStatusList);
					_likeStatusToSend = null;
				}
			}
		}
		yield return null;
		_blockSend = false;
		_sendCoroutine = null;
	}

	public string SerializeMessages(Dictionary<TypeGame, bool> tmpListStatusToSend)
	{
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append("{");
		foreach (KeyValuePair<TypeGame, bool> item in tmpListStatusToSend)
		{
			stringBuilder.Append("\"");
			stringBuilder.Append(BCWServer.GetIdModeByTypeGame(item.Key));
			stringBuilder.Append("\": ");
			stringBuilder.Append(item.Value ? 1 : (-1));
			stringBuilder.Append(',');
		}
		stringBuilder.Remove(stringBuilder.Length - 1, 1);
		stringBuilder.Append("}");
		return stringBuilder.ToString();
	}

	public void Init()
	{
		if (_likeStatusList != null)
		{
			return;
		}
		_likeStatusList = new Dictionary<TypeGame, bool>();
		List<object> list = Json.Deserialize(BCWStorage.Get<string>("likeModeStatusList")) as List<object>;
		List<int> list2 = new List<int>();
		if (list != null)
		{
			foreach (object item in list)
			{
				list2.Add(Convert.ToInt32(item));
			}
		}
		foreach (GameModeConfig.ModeInfo item2 in GameModeManager.instance.ModesConfig)
		{
			int idModeByTypeGame = BCWServer.GetIdModeByTypeGame(item2.typeGame);
			if (idModeByTypeGame >= 0)
			{
				_likeStatusList.Add(item2.typeGame, list2.Contains(idModeByTypeGame));
			}
		}
		_oldLikeStatusList = new Dictionary<TypeGame, bool>(_likeStatusList);
	}

	private IEnumerator InitLikeModesCoroutine()
	{
		while (!BCWServer.TryParseIdPlayer(BCWServer.idPlayer))
		{
			yield return null;
		}
		WWWForm form = new WWWForm();
		form.AddField("action", "get_rating_mode");
		form.AddField("id", BCWServer.idPlayer);
		form.AddField("app_version", BCWServer._version);
		WWW www = new WWW(headers: new Dictionary<string, string> { 
		{
			"Authorization",
			BCWServer.HashForPush(form.data)
		} }, url: URLs.bcwServer, postData: form.data);
		if (www == null)
		{
			Log("get_rating_mode Error www download");
			yield break;
		}
		yield return www;
		string result = BCWServer.Sanitize(www);
		if (!string.IsNullOrEmpty(www.error))
		{
			Log("get_rating_mode Error download:  " + www.error);
			yield break;
		}
		if (!string.IsNullOrEmpty(result) && result.Equals("fail"))
		{
			Log("get_rating_mode failed ");
			yield break;
		}
		if (string.IsNullOrEmpty(result))
		{
			Log("get_rating_mode result is empty");
			yield break;
		}
		Log("get_rating_mode result " + result);
		Dictionary<string, object> responseDictionary = Json.Deserialize(result) as Dictionary<string, object>;
		if (responseDictionary != null)
		{
			BCWStorage.Set("likeModeRating", result);
			_responseResult = result;
		}
	}

	private Dictionary<int, int> ResponseDictionayeParser(string result)
	{
		Dictionary<int, int> dictionary = new Dictionary<int, int>();
		Dictionary<string, object> dictionary2 = Json.Deserialize(result) as Dictionary<string, object>;
		if (dictionary2 != null)
		{
			foreach (KeyValuePair<string, object> item in dictionary2)
			{
				int num = Convert.ToInt32(item.Key);
				TypeGame typeGameByIdMode = BCWServer.GetTypeGameByIdMode(num);
				if (typeGameByIdMode != TypeGame.Unknown)
				{
					dictionary.Add(num, Convert.ToInt32(item.Value));
				}
			}
		}
		return dictionary;
	}

	private bool _checkSend()
	{
		BCWDebug.LogError(_oldLikeStatusList.ToStringFull());
		BCWDebug.LogError(_likeStatusList.ToStringFull());
		_likeStatusToSend = new Dictionary<TypeGame, bool>();
		foreach (KeyValuePair<TypeGame, bool> likeStatus in _likeStatusList)
		{
			if (_oldLikeStatusList.ContainsKey(likeStatus.Key) && likeStatus.Value != _oldLikeStatusList[likeStatus.Key])
			{
				_likeStatusToSend.Add(likeStatus.Key, likeStatus.Value);
			}
		}
		return _likeStatusToSend.Count > 0;
	}

	private void Log(string str)
	{
	}
}
